﻿using System.Collections.Generic;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;

namespace Language.Intellisense.QuickInfo
{
    internal class Controller : IIntellisenseController
    {
        #region Private Data

        private ITextView _textView;
        private IList<ITextBuffer> _subjectBuffers;
        private IQuickInfoBroker _broker;
        private IQuickInfoSession _session;

        #endregion Private Data

        #region C-Tor

        public Controller( ITextView textView, IList<ITextBuffer> subjectBuffers, IQuickInfoBroker broker )
        {
            _textView = textView;
            _subjectBuffers = subjectBuffers;
            _broker = broker;

            _textView.MouseHover += _textView_MouseHover;
        }

        #endregion C-Tor

        #region Event Handlers

        private void _textView_MouseHover( object sender, MouseHoverEventArgs e )
        {
            SnapshotPoint? point = _textView.BufferGraph.MapDownToFirstMatch( new SnapshotPoint( _textView.TextSnapshot, e.Position ), PointTrackingMode.Positive, snapshot => _subjectBuffers.Contains( snapshot.TextBuffer ), PositionAffinity.Predecessor );

            if ( point == null )
                return;

            ITrackingPoint trackingPoint = _textView.TextSnapshot.CreateTrackingPoint( point.Value.Position, PointTrackingMode.Positive );

            if ( !_broker.IsQuickInfoActive( _textView ) )
                _session = _broker.TriggerQuickInfo( _textView, trackingPoint, true );
        }

        #endregion Event Handlers

        #region IIntellisenseController

        void IIntellisenseController.Detach( ITextView textView )
        {
            if ( _textView != null )
            {
                _textView.MouseHover -= _textView_MouseHover;
                _textView = null;

            }
        }

        void IIntellisenseController.ConnectSubjectBuffer( ITextBuffer subjectBuffer )
        {
        }

        void IIntellisenseController.DisconnectSubjectBuffer( ITextBuffer subjectBuffer )
        {
        }

        #endregion IIntellisenseController
    }
}
